package com.gitee.fitness.service.impl;

import com.gitee.fitness.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class MessageServiceImpl implements IMessageService, RabbitTemplate.ReturnsCallback, RabbitTemplate.ConfirmCallback {


    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendMessage(String exchange, String routingKey, Object msg) {
        //消息发送失败返回到队列中, yml需要配置 publisher-returns: true
        rabbitTemplate.setMandatory(true);
        //消息消费者确认收到消息后，手动ack回执
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        //发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, msg);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info(" 回调id:{}", correlationData);
        if (ack) {
            log.info("消息成功发送");
        } else {
            log.info("消息发送失败:{}", cause);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage re) {
        log.info("Returned: {}\n" +
                        "replyCode: {}\n" +
                        "replyText: {}\n" +
                        "exchange: {}\n" +
                        "routingKey: {}",
                re.getMessage(),
                re.getReplyCode(),
                re.getReplyText(),
                re.getExchange(),
                re.getRoutingKey());

    }
}
